import axios from 'axios'
import qs from 'qs'
import { Message } from "element-ui";


const Axios = axios.create({
    baseURL: "http://127.0.0.1:20000/sys",
    timeout: 5000,
    responseType: "json",
    withCredentials: false, // 是否允许带cookie这些
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
Axios.interceptors.request.use(
    config => {
        if (
            config.method === 'post' ||
            config.method === 'put' ||
            config.method === 'delete'
        ) {
            config.data = qs.stringify(config.data);
        }
        if (localStorage.token) {
            config.headers.Authorization = localStorage.token;
        }
        return config;
    },
    error => {
        Message({
            showColse: true,
            message: '请求错误',
            type: 'error'
        });
        return Promise.reject(error);
    }
)

Axios.interceptors.response.use(
    response => {
        if (response.data.code != 0) {
            return Promise.reject(response.data);
        }
        return response;
    },
    error => {
        Message({
            showColse: true,
            message: '返回错误',
            type: 'error'
        })
        return Promise.reject(error);
    }
);

function fetch(url, params) {
    return new Promise((resolve, reject) => {
        Axios.post(url, params)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch(error => {
                reject(error)
            })
    });
}

export default {
    fetch
}